package com.bluishoul.kittymeow.mvc;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bluishoul.kittymeow.action.UserAction;

public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ActionServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public static final String USER_ACTION = "user";
	public static final String USER_LOGIN = "login";
	public static final String USER_LOGOUT = "logout";
	public static final String USER_REG = "reg";
	
	public String cpath;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		
		cpath = request.getContextPath();
		
		String action = request.getParameter("action");
		String method = request.getParameter("method");
		String return_string = "";
		
		RequestContext ctx = new RequestContext(request, response);

		try {

			if (USER_ACTION.equals(action)) {
				
				UserAction user_action = new UserAction(ctx);
				
				if (USER_LOGIN.equals(method)) {
					
					return_string = user_action.login();
					
				}else if(USER_LOGOUT.equals(method)){
					
					user_action.logout();
											
					response.sendRedirect(cpath);
						
					return;
											
				}else if(USER_REG.equals(method)){
					
					return_string = user_action.register();
					
				}
				
			}else{
				
				response.sendRedirect(cpath);
				
			}

		} catch (Exception ex) {
			return_string = _exceptionHandler(ex);
		}

		PrintWriter out = response.getWriter();
		out.write(return_string);
		out.flush();
		out.close();
	}

	private String _exceptionHandler(Exception ex) {
		return "{error:'"+ex.getMessage()+"'}";
	}

}
